package com.imti.retrofitweatherdemo;

import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.imti.retrofitweatherdemo.logic.INewsDetailLogic;
import com.imti.retrofitweatherdemo.logic.NewsDetail;
import com.imti.retrofitweatherdemo.logic.NewsDetailLogic;

public class NewsDetailActivity extends AppCompatActivity implements INewsDetailLogic
{

    private static final String TAG = NewsDetailActivity.class.getSimpleName();

    private TextView detailTitle;

    private WebView detailWeb;

    private NewsDetailLogic newsDetailLogic;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);

        initData();

        initView();
    }

    private void initData()
    {
        String uniqueKey = getIntent().getStringExtra("news_id");

        newsDetailLogic =
            NewsDetailLogic.getInstance((BaseApplication) getApplication(),
                this);
        newsDetailLogic.setiNewsLogic(this);

        newsDetailLogic.requestNewsDetail(uniqueKey);
    }

    private void initView()
    {
        ImageView backBtn = findViewById(R.id.news_detail_title_back);
        detailTitle = findViewById(R.id.news_detail_title_name);
        detailWeb = findViewById(R.id.news_detail_web);

        //WebView基本配置类
        WebSettings settings = detailWeb.getSettings();
        //是否允许执页面的JavaScript代码
        settings.setJavaScriptEnabled(true);
        //是否允许页面JavaScript开启新页面
        settings.setJavaScriptCanOpenWindowsAutomatically(true);

        //webview请求配置类（WebKit配置）
        WebViewClient client = new WebViewClient()
        {
            //页面点击链接后的回调方法
            //返回值：true：连接不跳转到系统浏览器；false：连接跳转系统浏览器
            @Override
            public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event)
            {
                return true;
            }
        };

        detailWeb.setWebViewClient(client);

        backBtn.setOnClickListener(v -> finish());
    }
    @Override
    public void requestNewsDetail(NewsDetail detail)
    {
//        detailTitle.setText(detail.getTitle());
//        detailWeb.loadData(detail.getContent(),null,null);
        detailWeb.loadUrl(detail.getUrl());

        //Android调用JS方法
//        String jsMethod = "javascript:setter(" + detail.getAuthor() + ")";
//        detailWeb.loadUrl(jsMethod);
//
//        detailWeb.evaluateJavascript("getter()", new ValueCallback<String>()
//        {
//            @Override
//            public void onReceiveValue(String value)
//            {
//                Log.d(TAG, "js 返回值：" + value);
//            }
//        });
    }
}